import java.util.LinkedList;
import java.util.Queue;

/**
 * 225. 用队列实现栈
 * https://leetcode-cn.com/problems/implement-stack-using-queues/
 */
public class Solutions_225 {
    public static void main(String[] args) {
        MyStack obj = new MyStack();
        obj.push(1);
        obj.push(2);
        int param_2 = obj.top();  // output: 2
        System.out.println(param_2);
        int param_3 = obj.pop();  // output: 2
        System.out.println(param_3);
        boolean param_4 = obj.empty();  // output: false
        System.out.println(param_4);
    }
}

class MyStack {
    // 按题意：定义队列，使用队列实现栈（先进后出，后进先出）
    private Queue<Integer> queue;

    /** Initialize your data structure here. */
    public MyStack() {
        queue = new LinkedList<>();
    }

    /** Push element x onto stack. */
    public void push(int x) {
        // 按队列结构，每次进入的元素都是在队尾，那么无法保证，pop 时能够弹出队尾的元素
        queue.add(x);
        // 循环将队尾前的元素，进行弹出并添加到队尾的操作，如此，保证 pop 时一定弹出的是 x 元素
        for (int i = 0; i < queue.size() - 1; i++) {
            queue.add(queue.poll());
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.poll();
    }

    /** Get the top element. */
    public int top() {
        return queue.peek();
    }

    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.size() == 0;
    }
}
